package com.example.heathy_me.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.example.heathy_me.MyApplication;
import com.example.heathy_me.R;
import com.example.heathy_me.utils.FriendList;
import com.example.heathy_me.utils.RequestHelper;
import com.example.heathy_me.utils.data;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Friend extends Fragment {
    private ImageView add;
    private LinearLayout add_friend;
    private EditText friend_name;
    private Button add_btn;
    private Boolean is_add=false;
    private MyAdapter adapter;
    MyApplication app;
    //每一列的列名/Map的键名  和其对应的View子控件的ID
    String[] from={"userPhoto","userName","userSign"};           //这里的内容对应后面HashMap中的键
    int[] to={R.id.ct_photo,R.id.ct_name,R.id.ct_sign};

    //整个ListView所显示的全部信息和资源数组
    int[] photoRes={R.drawable.ic_launcher_background,R.drawable.ic_launcher_background,R.drawable.ic_launcher_background,R.drawable.ic_launcher_background};
    String[] strName={"暗夜之殇","街角的幸福","静悄悄","愤怒的小胖"};
    String[] strSign={"Where is my love...","有些事终于想开了","总有一天会寻找到自己的幸福","谁再叫我小胖我跟谁急..."};
    List<data> friendList=new ArrayList<data>();
    //数据链表和Map容器
    ArrayList<HashMap<String,Object>> list=null;
    HashMap<String,Object> map=null;

    ListView listView=null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.friend,container,false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        app = (MyApplication) getActivity().getApplication();
        add = (ImageView)getActivity().findViewById(R.id.add);
        listView=(ListView)getActivity().findViewById(R.id.list);
        list=new ArrayList<HashMap<String,Object>>();
        add_friend = (LinearLayout)getActivity().findViewById(R.id.add_friend);
        friend_name = (EditText)getActivity().findViewById(R.id.friend_name);
        add_btn = (Button)getActivity().findViewById(R.id.add_btn);
        set_friend();

        add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    change_mode();
                }
            });
        add_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String  friend = friend_name.getText().toString();
                //如果输入为空
                if(friend.isEmpty())
                {
                    Toast.makeText(getContext(), "请输入帐号！", Toast.LENGTH_LONG).show();
                }
                else{
                    if(add_friend(friend))
                    {
                        Toast.makeText(getContext(), "添加成功！", Toast.LENGTH_LONG).show();
                        set_friend();
                    }
                    else {
                        Toast.makeText(getContext(), "添加失败！", Toast.LENGTH_LONG).show();
                    }


                }
            }
        });
    }
    void change_mode()
    {
        if(is_add)
        {
            add_friend.setVisibility(View.GONE);
            add.setImageResource(R.drawable.add);
        }
        else {
            add_friend.setVisibility(View.VISIBLE);
            add.setImageResource(R.drawable.sub);
        }
        is_add = !is_add;
    }
    Boolean add_friend(String username)
    {
        RequestHelper req = new RequestHelper();
        Map map = new HashMap();
        map.put("user_id", app.getUser().getId());
        map.put("username", username);
        JSONObject json = new JSONObject(map);
        try {
            String json_str = req.friend_post(app.getUrl()+"friend/add",json.toString());
            JSONObject jsonObject = new JSONObject(json_str);
            int status = jsonObject.getInt("status");
            if (status==1){
                return true;
            }else {
                return false;
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            return false;
        }

    }
    void get_friendlist() throws IOException {
        RequestHelper req = new RequestHelper();
        String json = req.friend_get(app.getUrl()+"friend/"+ app.getUser().getId());

        Gson gson = new Gson();
        //把JSON数据转化为对象
        FriendList friend = gson.fromJson(json, FriendList.class);
        friendList = friend.getData();
    }
    void set_friend()
    {
        try {
            get_friendlist();
            list = new ArrayList<HashMap<String,Object>>();
            for(int i=0; i<friendList.size(); i++){
                map=new HashMap<String,Object>();    //map调用put方法添加键值对
                map.put("userPhoto",getResources().getDrawable(R.drawable.admin));
                map.put("userName", friendList.get(i).getUsername());
                if (friendList.get(i).getTitle() == null)
                    map.put("userSign","暂无吃药动态");
                else
                    map.put("userSign",friendList.get(i).getTitle());
                map.put("id",friendList.get(i).getFriend_id());
                list.add(map);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        //创建自定义的MyAdapter对象
        adapter=new MyAdapter(getActivity(),R.layout.friendlist,list,from,to);

        //调用ListView的setAdapter()方法设置适配器
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
}

